var api = require("./utils/api.js");
const config = require("./utils/config")

Array.prototype.remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.add = function (val) {
  var index = this.indexOf(val);
  if (index < 0) {
    this.push(val)
  }
};

Array.prototype.contain = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    return true;
  } else {
    return false;
  }
};

App({
  onLaunch: async function () {
    let that = this
    wx.BaaS = requirePlugin('sdkPlugin')
    //让插件帮助完成登录、支付等功能
    wx.BaaS.wxExtend(wx.login,
     wx.getUserInfo)
    wx.BaaS.init('77ee94b3bf0ea8561be5')
    that.read()

    wx.BaaS.auth.loginWithWechat().then(user => {
      console.log(user)
      const parts = user.openid.split('_');
      const result = parts.pop(); // 获取最后一个元素
      that.globalData.openid = result;
      that.save()
    }, err => {
      // 登录失败
    })  
  },
  
  addCarNo : function(number) {
    this.globalData.card_list.push(number)
    this.save()
  },
  
  read() {
    const store = wx.getStorageSync('store')
     
    if (store) {
      this.globalData = store;
      console.log("read finish", this.globalData)
    }
  },

  save() {
    wx.setStorageSync('store', this.globalData)
  },

  validateOpenid : function() {
    let that = this;
    return new Promise((resolve,reject)=>{
      if (that.globalData.openid.length < 4) {
        wx.login({
          success: (res) => {
            wx.request({
              url: config.website + "/animal/getwxopenid",
              method: "POST",
              data: {
                code: res.code,
                site: 0
              },
              success: function (res) {
                that.globalData.openid = res.data.data.openid;
                that.save();
                resolve();
              }
            })
          },
        })
      } else {
        resolve();
      }
    })
  },

  async loginUser() {
    const params = {
      openid : this.globalData.openid
    }
    
    const res =  await api.loginUser(params);
    if (res.data.code == 200) {
      this.globalData = res.data.data;
      this.save()
      console.log("get", this.globalData)
    }

    return res.data.data
  },

  globalData: {
    openid : "",
    code : ""
  },
})